package com.borrow.jiemihua.base;

import android.Manifest;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.push.PushProxy;
import com.borrow.jiemihua.utils.ExceptionHelper;
import com.facebook.common.logging.FLog;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.listener.RequestListener;
import com.facebook.imagepipeline.listener.RequestLoggingListener;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;

import org.xutils.x;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import cc.duduhuo.custoast.CusToast;
import cn.tongdun.android.shell.FMAgent;
import cn.tongdun.android.shell.exception.FMException;

/**
 * Created by litao
 * 注释:application管理
 * Created by 2017/12/7.
 */

public class BaseApplication extends Application {

    public static Context context;
    public static BaseApplication mInstance;
    public int isWXPay = 100;
//    public final String WXAPP_ID = "wxd719b80668fd74ab";
    public final String WXAPP_ID = "wx36aeaed8c5cca88b";
    public Map<String, Object> sign_map;
    public static BaseApplication getInstance() {
        if (mInstance == null) {
            mInstance = (BaseApplication) context.getApplicationContext();
        }
        return mInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        x.Ext.init(this);
        context = getApplicationContext();
        initUncaughtException();
        initShareKey();
        MobclickAgent.onResume(this);
        //个推注册
        PushProxy.initPushService(this.getApplicationContext());
        int version = getAndroidSDKVersion();
        if (version == 0 || version < 14) {
            Toast.makeText(this, "该APP需运行在4.0及以上的安卓系统上！", Toast.LENGTH_SHORT)
                    .show();
        }
        // TODO: 2017/4/23 0023  切换正式环境 PRODUCT （测试环境SEND）
        try {
            FMAgent.init(context, BaseApplication.isTestServer()?BaseConstant.FMAGENTSEND:BaseConstant.FMAGENTPRO);
        } catch (FMException e) {
            e.printStackTrace();
        }
// TODO: 启动fresco日志信息 2016/11/15 adb logcat -v threadtime | grep -iE 'LoggingListener|AbstractDraweeController|BufferedDiskCache'
        Set<RequestListener> requestListeners = new HashSet<>();
        requestListeners.add(new RequestLoggingListener());
        ImagePipelineConfig config = ImagePipelineConfig.newBuilder(context)
                // other setters
                .setRequestListeners(requestListeners)
                .build();
        Fresco.initialize(context, config);
        FLog.setMinimumLoggingLevel(FLog.VERBOSE);
       CusToast.init(this);
    }
    /**
     * 初始化友盟
     */
    private void initShareKey() {
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
        PlatformConfig.setWeixin("wx36aeaed8c5cca88b", "43b0a102f50bff0e465b9d462c864921");
        PlatformConfig.setQQZone("1106614301", "T0vUtmqq1LU49kxG");
    }
    private void initUncaughtException() {
        ExceptionHelper helper = ExceptionHelper.getInstance();
        helper.init(this);
    }

    /**
     * 获取APP的版本号
     *
     * @return
     */
    public static String getVersion() {
        // 包管理器
        PackageManager pm = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = pm.getPackageInfo(context.getPackageName(), 0);
            Log.d("当前版本号：" ,packInfo.versionName.toString());
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }

    }

    /**
     * 获取APP的VersionCode
     *
     * @return
     */
    public static int getVersionCode() {
        // 包管理器
        PackageManager pm = context.getPackageManager();
        PackageInfo packInfo;
        try {
            packInfo = pm.getPackageInfo(context.getPackageName(), 0);
            Log.d("当前版本号Code：",""+ packInfo.versionCode);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }

    }

    /**
     * 获取sdk的版本号
     */
    private int getAndroidSDKVersion() {
        int version ;
        try {
            version = Integer.valueOf(Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            return 0;
        }

        return version;
    }

    public static boolean checkPermission(Context context, String permission) {
        boolean result = false;
        if (Build.VERSION.SDK_INT >= 23) {
            try {
                Class<?> clazz = Class.forName("android.content.Context");
                Method method = clazz.getMethod("checkSelfPermission", String.class);
                int rest = (Integer) method.invoke(context, permission);
                if (rest == PackageManager.PERMISSION_GRANTED) {
                    result = true;
                } else {
                    result = false;
                }
            } catch (Exception e) {
                result = false;
            }
        } else {
            PackageManager pm = context.getPackageManager();
            if (pm.checkPermission(permission, context.getPackageName()) == PackageManager.PERMISSION_GRANTED) {
                result = true;
            }
        }
        return result;
    }
    public void removerUser() {
        SharedPreferences sp = getSharedPreferences("config", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }
    /**
     * 添加到销毁队列
     *
     * @param activity 要销毁的activity
     */
    private static Map<String, Activity> destoryMap = new HashMap<>();

    public static void addDestoryActivity(Activity activity, String activityName) {
        destoryMap.put(activityName, activity);
    }

    /**
     * 销毁指定Activity
     */
    public static void destoryActivity(String activityName) {
        Set<String> keySet = destoryMap.keySet();
        for (String key : keySet) {
            Activity activity = destoryMap.get(key);
            if (activity != null)
                activity.finish();

        }
    }
    public static String getDeviceInfo(Context context) {
        try {
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = null;
            if (checkPermission(context, Manifest.permission.READ_PHONE_STATE)) {
                device_id = tm.getDeviceId();
            }
            String mac = null;
            FileReader fstream;
            try {
                fstream = new FileReader("/sys/class/net/wlan0/address");
            } catch (FileNotFoundException e) {
                fstream = new FileReader("/sys/class/net/eth0/address");
            }
            BufferedReader in = null;
            if (fstream != null) {
                try {
                    in = new BufferedReader(fstream, 1024);
                    mac = in.readLine();
                } catch (IOException e) {
                } finally {
                    if (fstream != null) {
                        try {
                            fstream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (in != null) {
                        try {
                            in.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            Log.e("umengtestdevices", json.toString());
            return json.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isTestServer(){
        return BaseApplication.getInstance().getResources().getBoolean(R.bool.isTestServer);
    }

}
